package com.neusoft.neuiotms.dcam.workflow.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.EntityNotFoundException;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.activiti.dto.ProcessInstanceDTO;
import com.neusoft.bizcore.activiti.service.ProcessInstanceService;
import com.neusoft.bizcore.activiti.service.WorkOrderService;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.neuiotms.dcam.constant.DCAMConsts;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetLifeCycleDTO;
import com.neusoft.neuiotms.dcam.fixed.model.Asset;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetRepository;
import com.neusoft.neuiotms.dcam.fixed.service.AssetLifeCycleService;
import com.neusoft.neuiotms.dcam.fixed.service.AssetService;
import com.neusoft.neuiotms.dcam.workflow.converter.ITSMApproveConverter;
import com.neusoft.neuiotms.dcam.workflow.converter.ZhuanyiKJConverter;
import com.neusoft.neuiotms.dcam.workflow.dto.ITSMApproveDTO;
import com.neusoft.neuiotms.dcam.workflow.dto.ZhuanyiKJDTO;
import com.neusoft.neuiotms.dcam.workflow.model.ITSMApprove;
import com.neusoft.neuiotms.dcam.workflow.model.ZhuanyiItemKJ;
import com.neusoft.neuiotms.dcam.workflow.model.ZhuanyiKJ;
import com.neusoft.neuiotms.dcam.workflow.repository.ITSMApproveRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.ZhuanyiItemKJRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.ZhuanyiKJRepository;
import com.neusoft.neuiotms.dcam.workflow.service.ZhuanyiKJService;

import io.micrometer.core.instrument.util.StringUtils;

@Service
public class ZhuanyiKJServiceImpl implements ZhuanyiKJService {

    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private ProcessInstanceService processInstanceService;
    @Autowired
    private ZhuanyiKJRepository zhuanyiKJRepository;
    @Autowired
    private ZhuanyiKJConverter zhuanyiKJConverter;
    @Autowired
    private ITSMApproveRepository approveRepository;
    @Autowired
    private ITSMApproveConverter approveConverter;
    @Autowired
    private ZhuanyiItemKJRepository zhuanyiItemKJRepository;
    @Autowired
    private AssetRepository assetRepository;
    @Autowired
    private AssetService assetService;
    @Autowired
    private AssetLifeCycleService assetLifeCycleService;

    @Override
    @Transactional
    public ZhuanyiKJDTO create(final ZhuanyiKJDTO dto, final UserBean user) {

        final String taskId = dto.getTaskId();
        final ProcessInstanceDTO instance =
                this.workOrderService.submit(dto.getTitle(), DCAMConsts.PROCESSS_ZHUANYI_KJ_KEY, dto.getWorkOrderNum(),
                        user);
        dto.setTaskId(instance.getTaskId());
        dto.setWorkOrderNum(instance.getWorkorderNum());
        dto.setCreateUser(user.getUsername());
        dto.setCreateUserName(user.getName());

        // 查询当前workOrderNum和TaskId下是否存在记录
        final ZhuanyiKJ oldModel = this.zhuanyiKJRepository.findByWorkOrderNumAndTaskId(
                dto.getWorkOrderNum(), taskId);
        if (oldModel == null) {
            dto.setId(null);
        }

        // 解锁以前的资产信息
        final List<ZhuanyiItemKJ> all = this.zhuanyiItemKJRepository.findByMain_WorkOrderNum(dto.getWorkOrderNum());
        if (null != all) {
            this.assetService.updateLocked(all.stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                    false);
        }

        ZhuanyiKJ model = this.zhuanyiKJConverter.toModel(dto);
        model = this.zhuanyiKJRepository.save(model);

        // 枷锁资产信息
        this.assetService.updateLocked(
                model.getDetails().stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                true);

        this.processInstanceService.setGlobalVariable(dto.getTaskId(), DCAMConsts.PROCESSS_ZHUANYI_KJ_QR_USER_KEY,
                dto.getZhuanyiUserCode());

        // 更新资产状态为转移中
        final List<String> codes = dto.getDetails().stream().map(l -> l.getCode()).distinct()
                .collect(Collectors.toList());
        this.assetService.updateStatus(codes, DCAMConsts.ASSET_STATUS_TRANSFER);

        // 完成当前节点
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);
        return this.zhuanyiKJConverter.toDTO(model);
    }

    @Override
    public ZhuanyiKJDTO detail(final String workOrderNum, final String taskId, final UserBean user) {
        ZhuanyiKJ model = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.zhuanyiKJRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        return new ZhuanyiKJDTO();
                    } else {
                        model = this.zhuanyiKJRepository.findByWorkOrderNumAndTaskId(workOrderNum,
                                lastTaskId);
                    }
                }
            } else if ("NULL".equals(taskId)) {
                final List<ZhuanyiKJ> ZhuanyiKJs =
                        this.zhuanyiKJRepository.findAllByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
                if ((ZhuanyiKJs != null) && (ZhuanyiKJs.size() > 0)) {
                    model = ZhuanyiKJs.get(0);
                }
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.zhuanyiKJConverter.toDTO(model);
    }

    @Override
    @Transactional
    public ITSMApproveDTO itsmCreate(final ITSMApproveDTO dto, final UserBean user) {
        final ITSMApprove model = this.approveConverter.toModel(dto);
        this.approveRepository.save(model);

        this.processInstanceService.setGlobalVariable(dto.getTaskId(), DCAMConsts.PROCESSS_ZHUANYI_KJ_APPROVE_RESULT,
                dto.getResult());
        // 完成当前节点
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);

        return this.approveConverter.toDTO(model);
    }

    @Override
    public ITSMApproveDTO itsmDetails(final String workOrderNum, final String taskId, final UserBean user) {
        ITSMApprove model = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.approveRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        return new ITSMApproveDTO();
                    } else {
                        model = this.approveRepository.findByWorkOrderNumAndTaskId(workOrderNum,
                                lastTaskId);
                    }
                }
            } else if ("NULL".equals(taskId)) {
                final List<ITSMApprove> ZhuanyiKJs =
                        this.approveRepository.findAllByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
                if ((ZhuanyiKJs != null) && (ZhuanyiKJs.size() > 0)) {
                    model = ZhuanyiKJs.get(0);
                }
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.approveConverter.toDTO(model);
    }

    @Transactional
    @Override
    public void confirmCreate(final ZhuanyiKJDTO dto, final UserBean user) {

        final List<ZhuanyiKJ> models =
                this.zhuanyiKJRepository.findAllByWorkOrderNumOrderByCreateTimeDesc(dto.getWorkOrderNum());

        if ((models != null) && (models.size() > 0)) {
            final ZhuanyiKJ model = models.get(0);
            // 修改位置
            dto.getDetails().forEach(l -> {
                model.getDetails().forEach(s -> {
                    if (l.getId().toString().equals(s.getId().toString())) {
                        s.setZhuanyiLocation(l.getZhuanyiLocation());
                        s.setZhuanyiLocationName(l.getZhuanyiLocationName());
                    }
                });
            });

            this.zhuanyiItemKJRepository.saveAll(model.getDetails());

            final List<ZhuanyiItemKJ> details = model.getDetails();
            this.zhuanyiKJCompleteUpdate(details, dto.getZhuanyiUserCode(), dto.getZhuanyiUserName());
        }

        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);
    }

    private void zhuanyiKJCompleteUpdate(final List<ZhuanyiItemKJ> details, final String zhuanyiUserCode,
            final String zhuanyiUserName) {

        final List<AssetLifeCycleDTO> lifeList = new ArrayList<>();

        final List<String> codes = details.stream().map(l -> l.getCode()).distinct()
                .collect(Collectors.toList());

        final List<Asset> assets = this.assetRepository.findByCodeIn(codes);
        if (null != assets) {
            assets.forEach(l -> {
                final List<ZhuanyiItemKJ> one =
                        details.stream().filter(s -> l.getCode().equals(s.getCode())).collect(Collectors.toList());
                l.setLocked(false);

                if ((one != null) && (one.size() > 0)) {
                    l.setLocation(one.get(0).getZhuanyiLocation());
                    l.setLocationName(one.get(0).getZhuanyiLocationName());
                }

                l.setManagementUserCode(zhuanyiUserCode);
                l.setManagementUserName(zhuanyiUserName);
                l.setStatus(DCAMConsts.ASSET_STATUS_USED);

                // 生命周期
                lifeList.add(AssetLifeCycleDTO.builder().code(l.getCode())
                        .lifeCycle(DCAMConsts.ASSET_LIFE_TYPE_ZHUANYI).workNum(one.get(0).getMain().getWorkOrderNum())
                        .content(l.getName() + "被转移了").build());

            });
            this.assetRepository.saveAll(assets);
            if (lifeList.size() > 0) {
                this.assetLifeCycleService.batchCreate(lifeList);
            }
        }

    }

    @Override
    public ZhuanyiKJDTO confirmDetails(final String workOrderNum, final String taskId, final UserBean user) {
        final List<ZhuanyiKJ> ZhuanyiKJs =
                this.zhuanyiKJRepository.findAllByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
        if ((ZhuanyiKJs != null) && (ZhuanyiKJs.size() > 0)) {
            return this.zhuanyiKJConverter.toDTO(ZhuanyiKJs.get(0));
        }
        return new ZhuanyiKJDTO();
    }

}
